<?php

	namespace app\common\middleware;

    use app\event\ucenter\User as UserEvent;
	use app\model\ucenter\User as UserModel;
	use think\exception\HttpResponseException;
    use think\facade\Config;
	use think\facade\Cookie;
	use think\facade\Request;
	use think\Response;

	/**
	 * 用户登录
	 */
	class UserGetLogin
	{
		public function handle($request, \Closure $next)
		{

            if (0 === strpos(strtolower($request->controller()), 'admin.'))
            {
                $module = 'admin';
            }
            elseif (false !== strpos(strtolower($request->controller()), '.admin.'))
            {
                $module = 'admin';
            }else{
                $module = explode('.',$request->controller())[0];

            }
			$request->auth_module = $module;
			$request->user = UserEvent::getLogin($module);

			return $next($request);
		}


		/**
		 * 检查权限.
		 * @param Request $request
		 * @param UserModel|null $user
		 * @param string $module
		 */
		protected function checkLogin($request, ?UserModel $user, string $module)
		{
			if (!$this->_needLogin($module, $request->controller(), $request->action())) {
				return true;
			} else {
				// 登陆检查
				// 未登陆进入登陆认证
				if (!$user) {
					// 缓存要登陆的模块
					Cookie::set('login_module', $module);
					if ($request->has('v')) {
						$url = url('/ucenter/login/' . $module);
						$html = '<title>404 页面不存在</title>
<div class="layui-fluid">
  <div class="layadmin-tips">
    <i class="layui-icon" face>&#xe664;</i>
    <div class="layui-text">
      <h2>
       <a href="' . $url . '">点我请重新登录</a>
      </h2>
    </div>
  </div>
</div>';
						$response = Response::create($html, 'html');
						throw new HttpResponseException($response);
					} else {
						// 缓存要访问的地址
						if ($module !== 'index') {
							Cookie::set('login_redirect', '/' . $module);
							$response = Response::create('/ucenter/login/' . $module, 'redirect', 302);
							throw new HttpResponseException($response);
						} else {
							Cookie::set('login_redirect', $request->url(true));
							$response = Response::create('/signin', 'redirect', 302);
							throw new HttpResponseException($response);
						}
					}
				} else {
					$user['last_active_time'] = time_format();
					$user->isAutoWriteTimestamp(false)->save();
				}
			}
		}

		/**
		 *  检查是否要登录
		 * @param $module
		 * @param $controller
		 * @param $action
		 * @return bool
		 */
		private function _needLogin($module, $controller, $action): bool
		{
			if (in_array($module, Config::get('auth.auth_module'))) {
				return true;
			}
			$controllers = explode('.', $controller);
			if (count($controllers) == 2 && strtolower($controllers[0]) == 'admin') {
				return true;
			}
			return false;
		}


	}